import 'dart:convert';
import 'dart:ui' as prefix0;

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_yres/pages/user/address/MyAddress.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/pages/user/address/address_entity.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';
import 'package:flutter_yres/pages/user/vip_order/OrderPay.dart';

class BuyGoodsPage extends StatefulWidget {
  String goods_name = "";
  String goods_id = "";
  String goods_img = "";
  String price = "";
  String skuJson = "";
  String skuInfo = "";
  String goods_num;
  String type = "0";
  String old = "0";
  String id = "0";
  BuyGoodsPage(
      {Key key,
      @required this.goods_id,
      @required this.goods_name,
      @required this.old,
      @required this.goods_img,
      @required this.price,
      @required this.skuJson,
      @required this.goods_num,
      this.type,
      this.id,
      @required this.skuInfo})
      : super(key: key);

  _BuyGoodsPageState createState() => _BuyGoodsPageState();
}

class _BuyGoodsPageState extends State<BuyGoodsPage>
    with WidgetsBindingObserver {
  var selectAddress = "";
  var selectId = "";
  var selectNameAndPhone = "";
  int num_buy = 1;
  String token = "";
  Map userMap = null;
  String remark = "";

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Container(
      child: new Scaffold(
        appBar: AppBar(
          title: Text('提交订单', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30), color: black)),
          backgroundColor: white,
          brightness: Brightness.light,
          iconTheme: IconThemeData(color: black_99),
          elevation: 1.0,
        ),
        resizeToAvoidBottomInset: false,
        body: SingleChildScrollView(
          child: new Container(
            color: white,
            // height: MediaQuery.of(context).size.height -
            //     kToolbarHeight -
            //     MediaQueryData.fromWindow(prefix0.window).padding.top,
            height:ScreenUtil.getInstance().setHeight(1100),
            child: new Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.all(15),
                  child: new Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Image.asset('images/icon_nav_location.png'),
                      Expanded(
                        child: GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.of(context).push<AddressListDataData>(
                                MaterialPageRoute(builder: (context) {
                              return MyAddressPage(
                                type: 1,
                              );
                            })).then((AddressListDataData data) {
                              print(data);
                              setState(() {
                                selectAddress = data.province +
                                    data.city +
                                    data.county +
                                    data.detail_address;
                                selectId = data.id;
                                selectNameAndPhone =
                                    data.consignee + "  " + data.contact_number;
                              });
                            });
                          },
                          child: selectAddress == ""
                              ? Padding(
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  child: Text('请选择收货地址',
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(NORMAL_FONT_SIZE),
                                          color: Colors.black45)))
                              : Padding(
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  child: new Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      Text(selectAddress,
                                          style: TextStyle(
                                              color: black,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(NORMAL_FONT_SIZE),
                                              fontWeight: FontWeight.w500)),
                                      Padding(
                                        padding:
                                            EdgeInsets.fromLTRB(0, 8, 0, 0),
                                        child: Text(selectNameAndPhone,
                                            style: TextStyle(
                                              color: black_99,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(SMALL_FONT_SIZE),
                                            )),
                                      )
                                    ],
                                  ),
                                ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context).push<AddressListDataData>(
                              MaterialPageRoute(builder: (context) {
                            return MyAddressPage(
                              type: 1,
                            );
                          })).then((AddressListDataData data) {
                            print(data);
                            setState(() {
                              selectAddress = data.province +
                                  data.city +
                                  data.county +
                                  data.detail_address;
                              selectId = data.id;
                              selectNameAndPhone =
                                  data.consignee + "  " + data.contact_number;
                            });
                          });
                        },
                        child: Container(
                          color: white,
                          child: Icon(Icons.arrow_forward_ios),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 5,
                  color: divideColor,
                  margin: EdgeInsets.fromLTRB(0, 5, 0, 10),
                ),
                Container(
                  padding: EdgeInsets.all(15),
                  child: new Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      widget.goods_img == ""
                          ? Image.asset(
                              'images/app_icon.png',
                              width: ScreenUtil.getInstance().setHeight(DP_120),
                              height:
                                  ScreenUtil.getInstance().setHeight(DP_120),
                              fit: BoxFit.fill,
                            )
                          : Image.network(
                              Api.BaseUrl + widget.goods_img,
                              width: ScreenUtil.getInstance().setHeight(DP_120),
                              height:
                                  ScreenUtil.getInstance().setHeight(DP_120),
                              fit: BoxFit.fill,
                            ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          padding: EdgeInsets.fromLTRB(10, 0, 5, 5),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                widget.goods_name,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE),
                                    color: black,
                                    fontWeight: FontWeight.w500),
                              ),
                              Padding(
                                padding: EdgeInsets.fromLTRB(0, 5, 5, 0),
                                child: Text(
                                  widget.skuInfo,
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(MINI_FONT_SIZE),
                                      color: black_99),
                                ),
                              ),
                              Text(
                                 MONEY + (widget.price),
                                style: TextStyle(
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(34),
                                    color: mainColor),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(15, 0, 10, 10),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text('购买数量',
                            style: TextStyle(color: black, fontSize: ScreenUtil.getInstance().setSp(33))),
                      ),
                      Row(
                        children: <Widget>[
                          new GestureDetector(
                            onTap: () {
                              if (widget.type == 'vip') {
                                //会员商品一次购买一个
                              } else {
                                if (num_buy <= 1) {
                                  return;
                                }
                                num_buy--;
                                setState(() {});
                              }
                            },
                            child: Icon(
                              Icons.remove,
                              color: black,
                              size: ScreenUtil.getInstance().setHeight(DP_30),
                            ),
                          ),
                          Text('  '),
                          Text(
                            num_buy.toString(),
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance().setSp(33),
                                color: black_99),
                          ),
                          Text('  '),
                          new GestureDetector(
                            onTap: () {
                              if (widget.type == 'vip') {
                                //会员商品一次购买一个
                              } else {
                                num_buy++;
                                setState(() {});
                              }
                            },
                            child: Icon(
                              Icons.add,
                              size: ScreenUtil.getInstance().setHeight(DP_30),
                              color: black,
                            ),
                          )
                        ],
                      )
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(0, 0, 10, 10),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text('',
                            style: TextStyle(color: black, fontSize: 14)),
                      ),
                      Text('共',
                          style: TextStyle(
                              color: black_99,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                      Text(num_buy.toString(),
                          style: TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                      Text('件商品，合计:',
                          style: TextStyle(
                              color: black_99,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                      Text(
                         MONEY + (widget.price),
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: mainColor),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text('订单备注',
                          style: TextStyle(
                              color: black,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                      Container(height: 5),
                      Container(
                          padding: EdgeInsets.all(5),
                          decoration: BoxDecoration(
                              color: f0Color,
                              borderRadius: BorderRadius.circular(5)),
                          child: new TextField(
                            keyboardType: TextInputType.numberWithOptions(),
                            maxLines: 2,
                            onChanged: (value) {
                              remark = value;
                            },
                            keyboardAppearance: Brightness.light,
                            cursorColor: mainColor,
                            // controller: userController,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                            decoration: new InputDecoration(
                                hintText: "订单备注不要超过50个字哦",
                                border: InputBorder.none,
                                hintStyle: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE))),
                          ))
                    ],
                  ),
                ),
                // Container(height: 5),
                // Container(
                //   height:5,
                //   color: divideColor,
                //   margin: EdgeInsets.fromLTRB(0, 5, 0, 10),
                // ),
                // Padding(
                //   padding: EdgeInsets.fromLTRB(10, 8, 10, 0),
                //   child: Row(
                //     children: <Widget>[
                //       Expanded(
                //         child: Text('商品总价',
                //             style: TextStyle(color: black, fontSize:ScreenUtil.getInstance().setSp(33))),
                //       ),
                //       Text(
                //         MONEY + (widget.price),
                //         style: TextStyle(
                //             fontSize: ScreenUtil.getInstance().setSp(33),
                //             color: mainColor),
                //       ),
                //     ],
                //   ),
                // ),
                // Padding(
                //   padding: EdgeInsets.fromLTRB(10, 8, 10, 0),
                //   child: Row(
                //     children: <Widget>[
                //       Expanded(
                //         child: Text('运费',
                //             style: TextStyle(color: black, fontSize: ScreenUtil.getInstance().setSp(33))),
                //       ),
                //       Text(
                //         '¥0.00',
                //         style: TextStyle(
                //             fontSize: ScreenUtil.getInstance().setSp(35),
                //             color: black_99),
                //       ),
                //     ],
                //   ),
                // ),
                Container(
                  height: 10,
                  color: divideColor,
                  margin: EdgeInsets.fromLTRB(0, 5, 0, 10),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(10, 5, 10, 0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text('实际付款',
                            style: TextStyle(color: black, fontSize: 14)),
                      ),
                      Text(
                        MONEY + (widget.price),
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(33),
                            color: Colors.black87),
                      ),
                    ],
                  ),
                ),
                // Padding(
                //   padding: EdgeInsets.fromLTRB(10, 3, 10, 10),
                //   child: Row(
                //     children: <Widget>[
                //       Expanded(
                //         child: Text('交单金额',
                //             style: TextStyle(color: black, fontSize: 14)),
                //       ),
                //       Text(
                //         MONEY +
                //             formatNum(
                //                 (double.parse(widget.price) * num_buy), 2),
                //         style: TextStyle(
                //             fontSize: ScreenUtil.getInstance().setSp(33),
                //             color: mainColor),
                //       ),
                //     ],
                //   ),
                // ),
                Expanded(
                  child: Container(
                    color: divideColor,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(10),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: Text(
                          MONEY +
                              formatNum(
                                  (double.parse(widget.price) * num_buy), 2),
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance().setSp(30),
                              color: mainColor),
                        ),
                      ),
                      new Container(
                        height: 35,
                        decoration: new BoxDecoration(
                            color: mainColor,
                            borderRadius: BorderRadius.circular(40.0)),
                        child: new FlatButton(
                          child: new Padding(
                            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            child: new Text(
                              "确定下单",
                              style: new TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE)),
                            ),
                          ),
                          onPressed: () {
                            if (selectId == "") {
                              Fluttertoast.showToast(msg: "请选择收货地址");
                              return;
                            }
                            showDialog(
                                context: context,
                                barrierDismissible: false,
                                builder: (_) {
                                  return new NetLoadingDialog(
                                    loadingText: "下单中...",
                                    bgColor: Color.fromARGB(255, 0, 0, 0),
                                    requestCallBack: null,
                                    outsideDismiss: false,
                                  );
                                });
                            buy();
                          },
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    num_buy = int.parse(widget.goods_num);
    getString(TOKEN).then((value) {
      token = value;
      address();
    });
  }

  address() async {
    //获取默认收货地址
    FormData data = new FormData.fromMap({'token': token});
    print(data);
    Response<String> response =
        await HttpUtil().post(Api.AddressListUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    AddressListEntity homeListEntity = new AddressListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (homeListEntity.data.datas.length > 0) {
          AddressListDataData data = homeListEntity.data.datas[0];
          selectAddress =
              data.province + data.city + data.county + data.detail_address;
          selectId = data.id;
          selectNameAndPhone = data.consignee + "  " + data.contact_number;
        }
      });
  }

  buy() async {
    // if (widget.type == "1") {
    //   Map map = new Map();
    //   map['token'] = token;
    //   map['id'] = widget.id;
    //   map['goods_sku'] = widget.skuJson;
    //   map['num'] = num_buy;
    //   map['remark']=remark;
    //   map['address_id'] = selectId;
    //   // map['sign_type'] = SignType.QIANGGOU_ORDER;
    //   Response<String> response =
    //       await HttpUtil().post(Api.QIANGGOU_ORDER, data: getSign(map));
    //   userMap = json.decode(response.data);
    //   int code = userMap['code'];
    //   Navigator.of(context).pop(1);
    //   if (code == 1) {
    //     Fluttertoast.showToast(msg: '下单成功');
    //     Navigator.of(context).pop("1");
    //     // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
    //     //   return new OrderPayPage(
    //     //       orderId: userMap['data']['order_id'],
    //     //       title: userMap['data']['title'],
    //     //       orderNum: userMap['data']['order_num'],
    //     //       totalMoney: userMap['data']['allprice'].toString());
    //     // }));
    //   } else {
    //     Fluttertoast.showToast(msg: userMap['msg']);
    //     userMap = null;
    //   }
    //   return;
    // }
    if (widget.type == 'vip') {
      Map map = new Map();
      map['token'] = token;
      map['goods_id'] = widget.goods_id;
      map['sku'] = widget.skuJson;
      map['address_id'] = selectId;
      map['num'] = '1';
      FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
        Response<String> response =
            await HttpUtil().post(Api.VipShopOrderUrl, data: data);
        Map userMap = json.decode(response.data);
        String msg = userMap["msg"];
        print(userMap);
         Fluttertoast.showToast(msg:msg);
        Navigator.of(context).pop(1);
        if (userMap['code'] == 1) {
          if (mounted) {
            // Fluttertoast.showToast(msg: '下单成功');
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
              return new OrderPayPage(
                  orderId: userMap['data']['order_id'],
                  title: userMap['data']['title'],
                  orderNum: userMap['data']['order_num'],
                  totalMoney: userMap['data']['pay_price'].toString());
            }));
          }
        }
    } else {
      Map map = new Map();
      map['token'] = token;
      map['goods_id'] = widget.goods_id;
      map['goods_sku'] = widget.skuJson;
      map['num'] = num_buy;
      map['address_id'] = selectId;
      // map['sign_type'] = SignType.BUY_GOODS;
      FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
      Response<String> response =
          await HttpUtil().post(Api.VipShopOrderUrl, data: data);
      userMap = json.decode(response.data);
      int code = userMap['code'];
      Navigator.of(context).pop(1);
      if (code == 1) {
        print(userMap);
        Fluttertoast.showToast(msg: '下单成功');
        Navigator.of(context).pop("1");
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return new OrderPayPage(
              orderId: userMap['data']['order_id'],
              title: userMap['data']['title'],
              orderNum: userMap['data']['order_num'],
              totalMoney: userMap['data']['pay_price'].toString());
        }));
      } else {
        Fluttertoast.showToast(msg: userMap['msg']);
        userMap = null;
      }
    }
  }
}
